package com.example.monitorsms;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.monitorsms.WindowManager.WindowController;
import com.example.monitorsms.WindowManager.WindowUtil;
import com.example.monitorsms.service.KeepAliveJobService;
import com.example.monitorsms.service.MyNotificationListenerService;
import com.example.monitorsms.service.MyService;
import com.example.monitorsms.utils.LogUtils;
import com.example.monitorsms.utils.SPUtils;
import com.example.monitorsms.utils.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends BaseActivity {
    private static final int REQUEST_CODE = 101;
    private boolean isActivate;
    private EditText etAudio, etTips, etPush;
    private TextView tvSetting, tvName;
    private AudioManager mAudioManager;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void main(Bundle savedInstanceState) {
        super.main(savedInstanceState);
        tvName = findViewById(R.id.tvName);
        tvSetting = findViewById(R.id.tvSetting);
        etAudio = findViewById(R.id.etAudio);
        etTips = findViewById(R.id.etTips);
        etPush = findViewById(R.id.etPush);

//        tvName.setText(getSmsInPhone());
//        tvName.setText("预警");
        mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        //获取媒体音量最大值
        int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        LogUtils.e("TAG", "max:" + max);
        tvSetting.setText("设备最大音量：" + max);
        Intent intent = new Intent(mContext, MyService.class);
        this.startService(intent);
        Intent intent1 = new Intent(mContext, MyNotificationListenerService.class);//启动服务
        startService(intent1);//启动服务
//        Intent intent_s = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
//        startActivity(intent_s);
        // 检查用户是否已经授予读取通知的权限
        if (!isNotificationListenerEnabled()) {
            // 请求用户授予读取通知的权限
            Intent intent_s = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
            startActivityForResult(intent_s, PERMISSION_REQUEST_CODE);
        }

        //在主进程启动所有服务
        startService(new Intent(mContext, KeepAliveJobService.class));
        //注册广播
        getApplicationContext().registerReceiver(mHomeKeyEventReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

        if (!WindowUtil.canOverDraw(mContext)) {
            //跳转到设置页面
            WindowUtil.jump2Setting(mActivity, REQUEST_CODE);
            return;
        }

        etTips.setText(SPUtils.get(mContext, "TipsOk", "交警") + "");
        etAudio.setText(SPUtils.get(mContext, "AudioOk", (int) (max / 2)) + "");
        etPush.setText(SPUtils.get(mContext, "PushOk", "交管") + "");
        MyApp.audioOk = (Integer) SPUtils.get(mContext, "AudioOk", (int) (max / 2));
        MyApp.tipsOk = SPUtils.get(mContext, "TipsOk", "交警") + "";
        MyApp.PushOk = SPUtils.get(mContext, "PushOk", "交管") + "";

        findViewById(R.id.tvTipsOk).setOnClickListener(v -> {
            String text = etTips.getText().toString().trim();
            if (!StringUtils.isEmpty(text)) {
                MyApp.tipsOk = text;
                SPUtils.put(mContext, "TipsOk", text);
                Toast.makeText(mContext, "已保存", Toast.LENGTH_SHORT).show();
            }
        });

        findViewById(R.id.tvAudioOk).setOnClickListener(v -> {
            String text = etAudio.getText().toString().trim();
            if (!StringUtils.isEmpty(text)) {
                MyApp.audioOk = Integer.valueOf(text);
                SPUtils.put(mContext, "AudioOk", MyApp.audioOk);
                Toast.makeText(mContext, "已保存", Toast.LENGTH_SHORT).show();
            }
        });

        findViewById(R.id.tvPushOk).setOnClickListener(v -> {
            String text = etPush.getText().toString().trim();
            if (!StringUtils.isEmpty(text)) {
                MyApp.PushOk = text;
                SPUtils.put(mContext, "PushOk", text);
                Toast.makeText(mContext, "已保存", Toast.LENGTH_SHORT).show();
            }
        });

        findViewById(R.id.tvTest).setOnClickListener(v -> {
            new Handler().postDelayed(() -> {
                MyApp.setVibrate();
                MyApp.setPlayer1();
            }, 500);
            new Handler().postDelayed(() -> {
                LogUtils.e("SmsRecevier", "是否震动了");
                if (MyApp.vibrator.hasVibrator()) {
                    LogUtils.e("SmsRecevier", "是的震动了");
                    MyApp.vibrator.cancel();
                }
            }, 5000);
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        isActivate = (Boolean) SPUtils.get(mContext, "isActivate", false);
        if (isActivate) {
            //关闭悬浮窗
            WindowController.getInstance().destroyThumbWindow();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        WindowController.getInstance().destroyThumbWindow();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (!WindowUtil.canOverDraw(this)) {
                //跳转到设置页面
                WindowUtil.jump2Setting(this, REQUEST_CODE);
                return true;
            }
            //开启悬浮窗
            WindowController.getInstance().showThumbWindow();
        }
        return super.onKeyDown(keyCode, event);
    }

    public String getSmsInPhone() {
        final String SMS_URI_ALL = "content://sms/"; // 所有短信
        final String SMS_URI_INBOX = "content://sms/inbox"; // 收件箱
        final String SMS_URI_SEND = "content://sms/sent"; // 已发送
        final String SMS_URI_DRAFT = "content://sms/draft"; // 草稿
        final String SMS_URI_OUTBOX = "content://sms/outbox"; // 发件箱
        final String SMS_URI_FAILED = "content://sms/failed"; // 发送失败
        final String SMS_URI_QUEUED = "content://sms/queued"; // 待发送列表

        StringBuilder smsBuilder = new StringBuilder();

        try {
            Uri uri = Uri.parse(SMS_URI_INBOX);
            String[] projection = new String[]{"_id", "address", "person", "body", "date", "type",};
            // 获取手机内部短信
            // Cursor cur = getContentResolver().query(uri, projection, null, null, "date desc");
            // 获取短信中最新的未读短信
            Cursor cur = getContentResolver().query(uri, projection, "read = ?", new String[]{"0"}, "date desc");
            if (cur.moveToFirst()) {
                int index_Address = cur.getColumnIndex("address");
                int index_Person = cur.getColumnIndex("person");
                int index_Body = cur.getColumnIndex("body");
                int index_Date = cur.getColumnIndex("date");
                int index_Type = cur.getColumnIndex("type");

                do {
                    String strAddress = cur.getString(index_Address);
                    int intPerson = cur.getInt(index_Person);
                    String strbody = cur.getString(index_Body);
                    long longDate = cur.getLong(index_Date);
                    int intType = cur.getInt(index_Type);

                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    Date d = new Date(longDate);
                    String strDate = dateFormat.format(d);

                    String strType = "";
                    if (intType == 1) {
                        strType = "接收";
                    } else if (intType == 2) {
                        strType = "发送";
                    } else if (intType == 3) {
                        strType = "草稿";
                    } else if (intType == 4) {
                        strType = "发件箱";
                    } else if (intType == 5) {
                        strType = "发送失败";
                    } else if (intType == 6) {
                        strType = "待发送列表";
                    } else if (intType == 0) {
                        strType = "所以短信";
                    } else {
                        strType = "null";
                    }

                    smsBuilder.append("[ ");
                    smsBuilder.append(strAddress + ", ");
                    smsBuilder.append(intPerson + ", ");
                    smsBuilder.append(strbody + ", ");
                    smsBuilder.append(strDate + ", ");
                    smsBuilder.append(strType);
                    smsBuilder.append(" ]\n\n");
                } while (cur.moveToNext());

                if (!cur.isClosed()) {
                    cur.close();
                    cur = null;
                }
            } else {
                smsBuilder.append("no result!");
            }

            smsBuilder.append("getSmsInPhone has executed!");
        } catch (SQLiteException ex) {
            LogUtils.e("SQLiteException in getSmsInPhone：" + ex.getMessage());
        }
        return smsBuilder.toString();
    }

    private static final int PERMISSION_REQUEST_CODE = 102;

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE:
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return;
                if (!WindowUtil.canOverDraw(mContext)) {
                    Toast.makeText(mContext, "悬浮窗权限未开启，请在设置中手动打开", Toast.LENGTH_SHORT).show();
                    return;
                }
                WindowController.getInstance().showThumbWindow();
                break;
            case RESULT_CANCELED:
                Toast.makeText(mContext, "用户不允许程序后台运行~", Toast.LENGTH_SHORT).show();
                break;
            case PERMISSION_REQUEST_CODE:
                // 检查用户是否已经授予读取通知的权限
                if (isNotificationListenerEnabled()) {
                    // 用户已经授予读取通知的权限，可以获取通知栏的通知了
                    // ...
                } else {
                    // 用户没有授予读取通知的权限，需要提示用户手动授予权限
                    Toast.makeText(this, "请授予读取通知的权限", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private boolean isNotificationListenerEnabled() {
        String packageName = getPackageName();
        String flat = Settings.Secure.getString(getContentResolver(),
                "enabled_notification_listeners");
        if (!TextUtils.isEmpty(flat)) {
            String[] names = flat.split(":");
            for (String name : names) {
                ComponentName componentName = ComponentName.unflattenFromString(name);
                if (componentName != null) {
                    if (TextUtils.equals(packageName, componentName.getPackageName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
        String SYSTEM_REASON = "reason";
        String SYSTEM_HOME_KEY = "homekey";
        String SYSTEM_HOME_KEY_LONG = "recentapps";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            LogUtils.e("TAG", "action----:" + action);
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_REASON);
                LogUtils.e("TAG", "reason----:" + reason);
                if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
                    //表示按了home键,程序到了后台
                    if (WindowUtil.canOverDraw(getApplicationContext())) {
                        WindowController.getInstance().showThumbWindow();
                    }
                } else if (TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)) {
                    //表示长按home键,显示最近使用的程序列表
                    if (WindowUtil.canOverDraw(getApplicationContext())) {
                        WindowController.getInstance().showThumbWindow();
                    }
                }
            }
        }
    };
}